package com.bit.deom.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.bit.deom.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class HuToolController {

    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/getcaptcha")
    public void createCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        String code = lineCaptcha.getCode();
        System.out.println("生成验证码 + " + code);
        session.setAttribute(captchaProperties.getSession().getCode(), code);
        session.setAttribute(captchaProperties.getSession().getTime(),System.currentTimeMillis());
        response.setContentType("image/png");
        lineCaptcha.write(response.getOutputStream());
        response.getOutputStream().close();
    }

    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session) {
        if (!StringUtils.hasLength(captcha)) {
            return false;
        }
        if (System.currentTimeMillis() - (Long) session.getAttribute(captchaProperties.getSession().getTime()) > 1000 * 60 * 5) {
            return false;
        }
        String code = (String)session.getAttribute("captcha_code");
        if (code.equals(captcha)) {
            return true;
        }
        return false;
    }
}
